﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MySql.Data.MySqlClient;

namespace Gollie.Ajax
{
	public class UpdateVendorSettings : AjaxResult
	{
		public UpdateVendorSettings() : base(null) { }

		public UpdateVendorSettings(AjaxArg arg)
			: base(arg)
		{
		}

		protected override void Init(AjaxArg ajaxArg)
		{
			UpdateVendorSettingsArg arg = (UpdateVendorSettingsArg)ajaxArg;

			int userId = Convert.ToInt32(arg.tokenUser);

			logger.Info("Updating vendor settings by user {0} for vendor {1}...", arg.tokenUser);

			try
			{
				UserInfo ui = Database.Queries.GetUser(userId, true);
				if (ui == null)
					throw new Exception("Gebruiker niet gevonden.");

				bool allowRefund = arg.allowrefund == "1";

				Database.Queries.UpdateVendorSettings(ui.VendorId, allowRefund);

				//refresh session object.
				HttpContext.Current.Session["userinfo"] = Database.Queries.GetUser(userId, true);
			}
			catch (MySqlException mySqlEx)
			{
				this.ErrorCode = mySqlEx.Number;
				this.ErrorMessage = MySqlErrorCodes.GetInstance().GetMessage(mySqlEx);
				logger.Info("Updating vendor settings failed: {0}", this.ErrorMessage);
			}
			catch (Exception e)
			{
				if (this.ErrorCode == 0)
					this.ErrorCode = 99;

				this.ErrorMessage = e.Message;
				logger.Info("Updating vendor settings failed: {0}", this.ErrorMessage);
			}

		}
	}
}